﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SerieInterface;
using System.IO;
using System.Drawing;
using System.Net;

namespace MyInteractiveSerieList
{
    public class GetImages : IGetImages
    {
        WebClient wC = new WebClient();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Serie"></param>
        /// <returns></returns>
        public Image GetImage(string Serie)
        {
            string imageURL;

            DirectoryInfo dI = new DirectoryInfo("..\\ImagesTemp\\");
            if (!Directory.Exists(dI.FullName))
                Directory.CreateDirectory(dI.FullName);
            FileInfo fI = new FileInfo(dI.FullName + Serie + ".jpg");
            if (File.Exists(fI.FullName))
                return Image.FromFile(fI.FullName);

            imageURL = GetImageURL(Serie);

            if (string.IsNullOrEmpty(imageURL))
            {
                wC.Dispose();
                return null;
            }

            wC.DownloadFile(imageURL, fI.FullName);
            wC.Dispose();
            return Image.FromFile(fI.FullName);
        }

        private string GetImageURL(string Serie)
        {
            try
            {
                string firstURL = "http://www.google.se/search?q=imdb+" + Serie;
                string secondURL = wC.DownloadString(firstURL).Substring(
                    wC.DownloadString(firstURL).IndexOf("http://www.imdb.com/title/tt"), "http://www.imdb.com/title/tt0000001/".Length);
                string firstPage = wC.DownloadString(secondURL);
                string subString = firstPage.Substring(firstPage.IndexOf("img_primary"));
                string imageURL = subString.Substring(subString.IndexOf("img src=\"") + "img src=\"".Length,
                    subString.IndexOf("style") - subString.IndexOf("img src=\"") - "img src=\"".Length);
                
                return imageURL.Remove(imageURL.IndexOf(".jpg") + ".jpg".Length);
            }
            catch
            {
                return null;
            }
        }



    }

}
